<template>
  <div class="reagent-container">
    <!-- 筛选条件 -->
    <div class="filter-section">
      <div class="filter-group">
        <span class="filter-label">试剂名称</span>
        <input
          type="text"
          class="filter-input"
          placeholder="输入试剂名称"
          v-model="filters.name"
        />
      </div>

      <div class="filter-group">
        <span class="filter-label">供应商</span>
        <select class="filter-select" v-model="filters.supplier">
          <option value="">全部</option>
          <option v-for="supplier in suppliers" :key="supplier" :value="supplier">
            {{ supplier }}
          </option>
        </select>
      </div>

      <div class="filter-group">
        <span class="filter-label">安全等级</span>
        <select class="filter-select" v-model="filters.safety_level">
          <option value="">全部</option>
          <option v-for="level in safety_level" :key="level.value" :value="level.value">
            {{ level.label }}
          </option>
        </select>
      </div>
      <!-- 条件筛选部分的搜索按钮改为 -->
      <button class="search-button" @click="handleFilterSearch">
        <span>筛选</span>
      </button>
      <!--试剂弹框-->
      <div class="action-group">
        <button class="add-button" @click="addData">
          <span>新增</span>
        </button>
        <div class="modal" v-if="showAddModel">
          <div class="modal-content">
            <div class="modal-header">
              <h3>新增试剂</h3>
              <button class="close-btn" @click="showAddModel = false">&times;</button>
            </div>
            <div class="modal-body">
              <form @submit.prevent="submitAddForm">
                <div class="form-group">
                  <label>试剂名称</label>
                  <input type="text" v-model="addForm.name" required>
                </div>
                <div class="form-group">
                  <label>规格</label>
                  <input type="text" v-model="addForm.specification" required>
                </div>
                <div class="form-group">
                  <label>供应商</label>
                  <select v-model="addForm.supplier" required>
                    <option value="">请选择供应商</option>
                    <option v-for="supplier in suppliers" :key="supplier" :value="supplier">{{ supplier }}</option>
                  </select>
                </div>
                <div class="form-group">
                  <label>库存量</label>
                  <input type="number" v-model="addForm.stock" required>
                </div>
                <div class="form-group">
                  <label>存放位置</label>
                  <input type="text" v-model="addForm.location" required>
                </div>
                <div class="form-group">
                  <label>有效期</label>
                  <input type="date" v-model="addForm.expiry_date" required>
                </div>
                <div class="form-group">
                  <label>安全等级</label>
                  <select v-model="addForm.safety_level" required>
                    <option value="">请选择安全等级</option>
                    <option v-for="level in safety_level" :key="level.value" :value="level.value">{{ level.label }}</option>
                  </select>
                </div>
                <div class="form-actions">
                  <button type="button" class="cancel-btn" @click="showAddModel = false">取消</button>
                  <button type="submit" class="submit-btn">提交</button>
                </div>
              </form>
            </div>
          </div>
        </div>
        <button class="reset-button" @click="resetFilters">
          <span>重置</span>
        </button>
      </div>
    </div>

    <!-- 数据表格 -->
    <table class="data-table">
      <thead>
        <tr>
          <th class="text-center">试剂名称</th>
          <th class="text-center">规格</th>
          <th class="text-center">供应商</th>
          <th class="text-center">库存量</th>
          <th class="text-center">存放位置</th>
          <th class="text-center">有效期</th>
          <th class="text-center">安全等级</th>
          <th class="text-center">操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in reagentList" :key="item.id">
          <td class="text-center">{{ item.name }}</td>
          <td class="text-center">{{ item.specification }}</td>
          <td class="text-center">{{ item.supplier }}</td>
          <td class="text-center" :class="{'low-stock': item.stock < 5}">{{ item.stock }}</td>
          <td class="text-center">{{ item.location }}</td>
          <td class="text-center" :class="{'expired': isExpired(item.expiry_date)}">
            {{ formatDate(item.expiry_date) }}
          </td>
          <td class="text-center">
            <span :class="`safety-level-${item.safety_level}`">
              {{ getSafetyLevelLabel(item.safety_level) }}
            </span>
          </td>
          <td class="text-center">
            <button class="edit-button" @click="navigateToEdit(item.id)">
              <span>编辑</span>
            </button> |
            <!-- 编辑试剂弹窗 -->
            <div class="modal" v-if="showEditModel">
              <div class="modal-content">
                <div class="modal-header">
                  <h3>编辑试剂</h3>
                  <button class="close-btn" @click="showEditModel = false">&times;</button>
                </div>
                <div class="modal-body">
                  <form @submit.prevent="submitEditForm">
                    <div class="form-group">
                      <label>试剂名称</label>
                      <input type="text" v-model="editForm.name" required>
                    </div>
                    <div class="form-group">
                      <label>规格</label>
                      <input type="text" v-model="editForm.specification" required>
                    </div>
                    <div class="form-group">
                      <label>供应商</label>
                      <select v-model="editForm.supplier" required>
                        <option value="">请选择供应商</option>
                        <option v-for="supplier in suppliers" :key="supplier" :value="supplier">{{ supplier }}</option>
                      </select>
                    </div>
                    <div class="form-group">
                      <label>库存量</label>
                      <input type="number" v-model="editForm.stock" required>
                    </div>
                    <div class="form-group">
                      <label>存放位置</label>
                      <input type="text" v-model="editForm.location" required>
                    </div>
                    <div class="form-group">
                      <label>有效期</label>
                      <input type="date" v-model="editForm.expiry_date" required>
                    </div>
                    <div class="form-group">
                      <label>安全等级</label>
                      <select v-model="editForm.safety_level" required>
                        <option value="">请选择安全等级</option>
                        <option v-for="level in safety_level" :key="level.value" :value="level.value">{{ level.label }}</option>
                      </select>
                    </div>
                    <!-- 其他表单字段与新增表单类似 -->
                    <div class="form-actions">
                      <button type="button" class="cancel-btn" @click="showEditModel = false">取消</button>
                      <button type="submit" class="submit-btn">保存</button>
                    </div>
                  </form>
                </div>
              </div>
            </div>
            <button class="delete-button" @click="deleteItem(item.id)">
              <span>删除</span>
            </button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 分页 -->
    <div class="pagination-right">
      <div class="page-size">
        <span>每页显示：</span>
        <select v-model="pagination.pageSize" @change="handleSizeChange">
          <option value="10">10</option>
          <option value="20">20</option>
          <option value="50">50</option>
        </select>
      </div>
      <div class="page-control">
        <button
          class="page-button"
          @click="prevPage"
          :disabled="pagination.currentPage === 1"
        >
          <span>上一页</span>
        </button>
        <span class="page-info">当前页：{{ pagination.currentPage }}</span>
        <button
          class="page-button"
          @click="nextPage"
          :disabled="pagination.currentPage >= totalPages"
        >
          <span>下一页</span>
        </button>
      </div>
      <div class="total-records">
        <span>共 {{ pagination.total }} 条记录</span>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  data () {
    return {
      showAddModel: false,
      showEditModel: false,
      addForm: {
        name: '',
        specification: '',
        supplier: '',
        stock: 0,
        location: '',
        expiry_date: this.formatDateForInput(new Date()),
        safety_level: ''
      },
      editForm: {
        id: '',
        name: '',
        specification: '',
        supplier: '',
        stock: 0,
        location: '',
        expiry_date: '',
        safety_level: '1'
      },
      reagentList: [],
      suppliers: [],
      safety_level: [],
      filters: {
        name: '',
        supplier: '',
        safety_level: ''
      },
      searchKeyword: '',
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    }
  },
  mounted () {
    this.getReagentList()
    this.formatDateForInput()
  },
  computed: {
    totalPages () {
      return Math.ceil(this.pagination.total / this.pagination.pageSize)
    }
  },
  methods: {
    formatDateForInput (date) {
      if (!date) return ''
      const d = new Date(date)
      const pad = num => (num < 10 ? '0' + num : num)
      return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
    },
    getReagentList () {
      axios.get('http://localhost:8000/api/reagent').then(response => {
        console.log('API返回数据', response.data)
        // 确保处理的是数组数据
        const reagentData = response.data.data || response.data
        const dataArray = Array.isArray(reagentData) ? reagentData : []

        // 更新试剂列表
        this.reagentList = dataArray

        // 从试剂列表中提取供应商（去重）
        this.suppliers = [...new Set(
          dataArray.map(item => item.supplier).filter(Boolean)
        )]

        // 安全等级数据（使用硬编码或从数据中提取）
        this.safety_level = [
          { value: 1, label: '普通' },
          { value: 2, label: '易燃' },
          { value: 3, label: '腐蚀性' },
          { value: 4, label: '有毒' }
        ]

        // 如果有分页数据，更新分页信息
        if (response.data.total !== undefined) {
          this.pagination.total = response.data.total
        }
      })
        .catch(error => {
          console.error('获取试剂列表失败:', error)
        })
    },
    submitAddForm () {
      axios.post('http://localhost:8000/api/reagent/', this.addForm).then(response => {
        this.getReagentList()
        this.pagination.total++
        this.showAddModel = false
        alert('添加成功')
      }).catch(error => {
        alert('添加失败', error)
      })
    },
    submitEditForm () {
      axios.put(`http://localhost:8000/api/reagent/${this.editForm.id}/`, this.editForm).then(response => {
        this.getReagentList()
        this.showEditModel = false
        alert('更新成功')
      }).catch(error => {
        console.error('更新失败', error)
        alert('更新失败')
      })
    },
    deleteItem (id) {
      if (confirm('确定要删除吗？')) {
        axios.delete(`http://localhost:8000/api/reagent/${id}/`).then(response => {
          this.getReagentList()
          this.pagination.total--
          alert('删除成功')
        }).catch(error => {
          console.error('删除失败', error)
          alert('删除失败')
        })
      }
    },
    addData () {
      this.showAddModel = true
      this.resetAddForm()
    },
    resetAddForm () {
      this.addForm = {
        name: '',
        specification: '',
        supplier: '',
        stock: 0,
        location: '',
        expiry_date: '',
        safety_level: ''
      }
    },
    async loadData () {
      try {
        // 构建查询参数
        const params = {
          page: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        }

        // 确定搜索模式
        if (this.searchKeyword) {
          // 关键词搜索模式
          params.search = this.searchKeyword
        } else {
          // 条件筛选模式
          if (this.filters.name) params.name = this.filters.name
          if (this.filters.supplier) params.supplier = this.filters.supplier
          if (this.filters.safety_level) params.safety_level = Number(this.filters.safety_level)
        }
        const response = await axios.get('http://localhost:8000/api/reagent/', { params })
        // 统一处理响应数据
        this.reagentList = response.data.data || response.data
        // 更新供应商和安全等级
        this.updateDropdownData(this.reagentList)
        // 更新分页信息
        if (response.data.total !== undefined) {
          this.pagination.total = response.data.total
        }
      } catch (error) {
        console.error('加载数据失败:', error)
      }
    },
    updateDropdownData (reagentList) {
      // 更新供应商列表
      this.suppliers = [...new Set(
        [...this.suppliers, ...reagentList.map(item => item.supplier)].filter(Boolean)
      )]

      // 更新安全等级列表
      const newLevels = [...new Set(
        reagentList.map(item => item.safety_level).filter(Boolean)
      )]

      newLevels.forEach(level => {
        if (!this.safety_level.some(l => l.value === level)) {
          this.safety_level.push({
            value: level,
            label: this.getSafetyLevelLabel(level)
          })
        }
      })
    },
    handleFilterSearch () {
      this.pagination.currentPage = 1
      this.searchKeyword = ''
      this.loadData()
    },
    resetFilters () {
      this.filters = {
        name: '',
        supplier: '',
        safety_level: ''
      }
      this.searchKeyword = ''
      this.pagination.currentPage = 1
      this.loadData()
    },
    handleSizeChange (val) {
      this.pagination.pageSize = Number(val)
      this.pagination.currentPage = 1
      this.loadData()
    },
    prevPage () {
      if (this.pagination.currentPage > 1) {
        this.pagination.currentPage--
        this.loadData()
      }
    },
    nextPage () {
      if (this.pagination.currentPage < this.totalPages) {
        this.pagination.currentPage++
        this.loadData()
      }
    },
    navigateToEdit (id) {
      const item = this.reagentList.find(item => item.id === id)
      if (item) {
        this.editForm = {
          id: item.id,
          name: item.name,
          specification: item.specification,
          supplier: item.supplier,
          stock: item.stock,
          location: item.location,
          expiry_date: this.formatDateForInput(item.expiry_date),
          safety_level: item.safety_level
        }
        this.showEditModel = true
      }
    },
    formatDate (dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    },
    isExpired (dateString) {
      return new Date(dateString) < new Date()
    },
    getSafetyLevelLabel (level) {
      const found = this.safety_level.find(item => item.value === level)
      return found ? found.label : ''
    }
  }
}
</script>

<style scoped>

.reagent-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

/* 筛选区域 */
.filter-section {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 20px;
  align-items: center;
}

.filter-group {
  display: flex;
  align-items: center;
}

.filter-label {
  margin-right: 5px;
  font-size: 14px;
  color: #333;
  min-width: 60px;
}

.filter-input {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 150px;
}

.filter-select {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 180px;
}

.action-group {
  display: flex;
  gap: 10px;
  margin-left: auto;
}

.search-button, .reset-button, .add-button, .page-button {
  display: flex;
  justify-content: center;
  align-items: center;
}
.action-separator {
  margin: 0 8px;
  color: #ddd;
}
/* 弹窗样式 */
.modal {
  position: fixed;
  top:60px;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255,255,255,0.05);
  backdrop-filter: blur(3px);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1003;
  animation: fadeIn 0.3s;
}
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
.modal-content {
  background-color: white;
  width: 70%;
  margin-top: -15px;
  max-width: 550px;
  border-radius: 5px;
  align-items: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}

.modal-header {
  padding: 12px 15px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
}
.modal-body {
  padding: 15px;
}

.form-group {
  margin-bottom: 14px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group input,
.form-group select {
  width: 90%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.cancel-btn {
  padding: 8px 16px;
  background-color: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-right: 10px;
  cursor: pointer;
}

.submit-btn {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.submit-btn:hover {
  background-color: #40a9ff;
}
.add-button {
  padding: 8px 16px;
  background-color: #4fbf30;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.add-button:hover {
  background-color: #7edd64;
}

.search-button {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.search-button:hover {
  background-color: #40a9ff;
}

.reset-button {
  padding: 8px 16px;
  background-color: #fff;
  color: #666;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.reset-button:hover {
  color: #1890ff;
  border-color: #1890ff;
}

/* 表格样式 */
.data-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

.data-table th {
  background-color: #f5f7fa;
  padding: 12px 16px;
  color: #333;
  font-weight: 500;
  border-bottom: 1px solid #e8e8e8;
}

.data-table td {
  padding: 12px 16px;
  border-bottom: 1px solid #e8e8e8;
}

.data-table tbody tr:hover {
  background-color: #f9f9f9;
}

.text-center {
  text-align: center;
}

/* 操作按钮 */
.edit-button {
  padding: 6px 12px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  transition: background-color 0.3s;
}

.delete-button {
  padding: 6px 12px;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  transition: background-color 0.3s;
  background-color: #f40909;
}

.delete-button:hover {
  background-color: #e36565;
}

.edit-button:hover {
  background-color: #40a9ff;
}

/* 分页样式 */
.pagination-right {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 20px;
}

.page-size {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-size select {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.page-control {
  display: flex;
  align-items: center;
  gap: 10px;
}

.page-button {
  padding: 6px 12px;
  background-color: #fff;
  color: #666;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.page-button:hover:not(:disabled) {
  color: #1890ff;
  border-color: #1890ff;
}

.page-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.page-info {
  font-size: 14px;
  color: #666;
}

.total-records {
  font-size: 14px;
  color: #666;
}

/* 状态样式 */
.low-stock {
  color: #f5222d;
  font-weight: bold;
}

.expired {
  color: #f5222d;
  font-weight: bold;
}

.safety-level-1 { color: #52c41a; }
.safety-level-2 { color: #faad14; }
.safety-level-3 { color: #fa8c16; }
.safety-level-4 { color: #f5222d; }
</style>
